package com.tang.java.template.freemarker;

import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.apache.commons.io.FileUtils;
import org.junit.Test;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zhr
 */
public class T1 {
    private static final String CHARSET = "UTF-8";
    @Test
    public void t01() throws IOException, TemplateException {
//        String str = readFileToString("", CHARSET);
//        Configuration conf = configuration();

        String templateName = "hello-template";
        String templateValue = "hello,${name}";
        Configuration configuration = configuration();
        processTemplate(configuration, templateName, templateValue);
        // -------------------- 进行模板的修改 ------------------------
        templateValue = "hello,${name},我今年,${age}岁.";
        processTemplate(configuration, templateName, templateValue);


    }

    @Test
    public void t02() {

    }

    /**
     * 解析模板
     *
     * @param configuration
     * @param templateName
     * @throws IOException
     * @throws TemplateException
     */
    private void processTemplate(Configuration configuration, String templateName, String templateValue) throws IOException, TemplateException {
        Map<String, Object> root = new HashMap<>();
        root.put("name", "你好");
        root.put("age", 25);
        StringWriter stringWriter = new StringWriter();
        Template template = new Template(templateName, templateValue, configuration);
        template.process(root, stringWriter);
        System.out.println(stringWriter.toString());
    }

    /**
     * 配置 freemarker configuration
     *
     * @return
     */
    private Configuration configuration() {
        Configuration conf = new Configuration(Configuration.VERSION_2_3_27);
        StringTemplateLoader templateLoader = new StringTemplateLoader();
        conf.setTemplateLoader(templateLoader);
        conf.setDefaultEncoding(CHARSET);
        return conf;
    }

    public String readFileToString(String fileName, String encoding) {
        try {
            return FileUtils.readFileToString(new File(fileName), encoding);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
